package com.aliengen.thingple.thingple.fillingstation;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.aliengen.thingple.thingple.AbstractThingpleActivity;
import com.aliengen.thingple.thingple.R;
import com.aliengen.thingple.thingple.api.AsyncTagUpdate;
import com.aliengen.thingple.thingple.fragment.CylindersFragment;
import com.aliengen.thingple.thingple.fragment.CylindersRecyclerViewAdapter;
import com.aliengen.thingple.thingple.fragment.YesNoDialog;
import com.aliengen.thingple.thingple.handler.BatchReadThread;
import com.aliengen.thingple.thingple.handler.CMCHandler;
import com.aliengen.thingple.thingple.tag.BundleTag;
import com.aliengen.thingple.thingple.tag.CylinderTag;
import com.aliengen.thingple.thingple.tag.Tag;
import com.aliengen.thingple.thingple.tag.TruckTag;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
public class CheckOutActivity extends AbstractThingpleActivity implements CylindersFragment.OnListFragmentListener, BatchReadThread.ReadingListener {

    protected TruckTag truckTag = null;
    protected BatchReadThread readThread = null;

    protected YesNoDialog alert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_check_out);
        setOperatorName();
        setCylinderCount(0);

        alert = new YesNoDialog();

        BatchReadThread.tagList.clear();
        BatchReadThread.operationId = 7; // CheckOut Platform

        mApplication.getHandler().setActivity(this);

        mApplication.getHandler().setOnEventListener(new CMCHandler.OnEventListener() {
            @Override
            public void onPressDown() {
                startReading();
            }

            @Override
            public void onPressUp() {
                stopReading();
            }

            @Override
            public void onReceiveData() {
                updateList();
            }

            @Override
            public void onRead(String data) {
            }

            @Override
            public void onReadFailed() {
            }

            @Override
            public void onWrite() {
            }

            @Override
            public void onWriteFailed() {
            }

            @Override
            public void onTagSelected() {

            }

            @Override
            public void onTagSelectFailed() {

            }
        });

        Bundle b = getIntent().getExtras();
        String truckPlateNumber = "";
        if (b != null) {
            this.truckTag = (TruckTag) b.get("truck_tag");
            truckPlateNumber = this.truckTag.getPlateNumber();
        } else {
            this.truckTag = null;
        }

        Resources res = getResources();
        String message = String.format(res.getString(R.string.truck_plate_number), truckPlateNumber);
        TextView truckPlateNumberView = (TextView) this.findViewById(R.id.truckPlateNumber);
        truckPlateNumberView.setText(message);
        truckPlateNumberView.invalidate();

        BatchReadThread.truckTag = this.truckTag;
    }

    public Boolean validate(Tag tag)
    {
        return tag instanceof CylinderTag || tag instanceof BundleTag;
    }

    public void onReadingException(Exception e)
    {

    }

    public void setCylinderCount(Integer count) {
        Resources res = getResources();
        String message = String.format(res.getString(R.string.cylinders_count), count.toString());
        TextView tView = (TextView) this.findViewById(R.id.cylindersCount);
        tView.setText(message);
        tView.invalidate();
    }

    public void updateList() {
        CylindersFragment fragment = (CylindersFragment) getSupportFragmentManager().findFragmentById(R.id.checkout_list);
        final CylindersRecyclerViewAdapter adapter = fragment.getAdapter();
        adapter.updateList(BatchReadThread.tagList);
        setCylinderCount(adapter.getItemCount());

        ArrayList<Tag> list = new ArrayList<Tag>(BatchReadThread.tagList.values());
        AsyncTagUpdate async = new AsyncTagUpdate();
        async.setApplication(mApplication);

        async.setOnExecuteListener(new AsyncTagUpdate.OnExecuteListener() {
            @Override
            public void onPostExecute() {
                showToast(R.string.cylinders_synchronized);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onProgressUpdate() {

            }

            @Override
            public void onMessage(String message) {
                showToast(message);
            }
        });

        if(!this.alert.isVisible() && !this.alert.isAdded()) {
            Iterator<Tag> iter = list.iterator();
            Boolean hasMaintenanceNeeded = false;
            while (iter.hasNext()) {
                Tag t = iter.next();
                if(t instanceof CylinderTag)
                if (((CylinderTag)t).hasProblem()) {
                    hasMaintenanceNeeded = true;
                    break;
                }
            }

            if (hasMaintenanceNeeded) {
                Bundle args = new Bundle();
                args.putString("title", getResources().getString(R.string.cylinders_alert_title));
                args.putString("message", getResources().getString(R.string.cylinders_alert_content));
                alert.setArguments(args);
                alert.show(getFragmentManager(), "tag");
            }
        }

        async.execute(list);
    }

    public void startReading() {
        if(readThread != null && readThread.isAlive())
        {
            showToast("Reading already launched!");
            return;
        }

        Button start = (Button) this.findViewById(R.id.button_start);
        Button stop = (Button) this.findViewById(R.id.button_stop);
        start.setVisibility(View.GONE);
        stop.setVisibility(View.VISIBLE);

        readThread = new BatchReadThread(mApplication, this);
        readThread.start();
    }

    public void stopReading() {
        if(readThread == null)
        {
            showToast("Reading already stopped!");
            return;
        }

        readThread.stopReading();
        Button start = (Button) this.findViewById(R.id.button_start);
        Button stop = (Button) this.findViewById(R.id.button_stop);
        stop.setVisibility(View.GONE);
        start.setVisibility(View.VISIBLE);
    }

    public void onListInteraction(Tag item) {
        if(item instanceof CylinderTag) {
            Intent nextScreen = new Intent(getApplicationContext(), CylinderActivity.class);
            nextScreen.putExtra("cylinder_tag", (CylinderTag)item);
            startActivity(nextScreen);
        }
        else
            if(item instanceof BundleTag)
            {
                Intent nextScreen = new Intent(getApplicationContext(), CylinderActivity.class);
                nextScreen.putExtra("bundle_tag", (BundleTag)item);
                startActivity(nextScreen);
            }
    }

    public void onClickStart(View v) {
        startReading();
    }

    public void onClickStop(View v) {
        stopReading();
    }
}
